package com.lrd.snapshotorder.config.datasource.shardingalgorithm;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.MultipleKeysTableShardingAlgorithm;
import com.lrd.snapshotorder.util.ShardingIdUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * 分表
 */
@Slf4j
public class MultipleKeysShardingTable implements MultipleKeysTableShardingAlgorithm {
    private static final int TABLE_COUNT = 32;

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, Collection<ShardingValue<?>> shardingValues) {
        Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
        for (ShardingValue<?> value : shardingValues) {
            String id = value.getValue() + "";
            long index = Long.parseLong(ShardingIdUtils.getLastNumber(ShardingIdUtils.getFirstNumber(id,6),4));
            for (String tableName : availableTargetNames) {
                if (tableName.endsWith(index % TABLE_COUNT + "")) {
                    result.add(tableName);
                    log.info("=================TABLE rule route:{}", tableName);
                    return result;
                }
            }
        }
        return result;
    }
}
